package com.boc.langxiang.presenter;


import android.support.annotation.Nullable;

import com.boc.langxiang.contract.ImageContract;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.manager.DataCleanManager;
import com.boc.langxiang.net.ApiService;
import com.boc.langxiang.net.NetClient;
import com.boc.langxiang.net.ResponseCode;
import com.boc.langxiang.net.okhttp.OkHttpUtils;
import com.boc.langxiang.net.okhttp.callback.StringCallback;
import com.boc.langxiang.net.okhttp.request.BaseRequest;
import com.boc.langxiang.net.okhttp.request.PostRequest;
import com.boc.langxiang.util.FileUtils;
import com.boc.langxiang.util.GsonUtil;
import com.google.gson.reflect.TypeToken;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;

/**
 * CreateTime: 2016-06-14上午10:40
 * Author: wjkjinke00@126.com
 * Description:
 */
public class ImagePresenter implements ImageContract.Presenter {

    private final ApiService mService;
    private ImageContract.View mView;

    public ImagePresenter(ImageContract.View view) {
        mService = NetClient.getInstance().net().create(ApiService.class);
        mView = view;
    }


    @Override
    public void uploadFile(String filrUrl) {
        PostRequest request = OkHttpUtils.post(NetClient.BASE_URL + NetClient.UPLOAD_IMAGE).tag(this);
        request.params("upload_file", new File(filrUrl));
        request.execute(new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                mView.showLoading();
            }

            @Override
            public void onResponse(String s) {
                mView.hideLoading();
                BaseResponse<String> baseResponse = GsonUtil.parseJson(s, new TypeToken<BaseResponse<String>>() {
                });

                if (baseResponse.getReturnNo().equals(ResponseCode.SUCCESS)) {
//                    delImageThread.start();
                    mView.uploadFileSuccess(baseResponse.getContent());
                } else {
                    mView.uploadFileFailed();
                }
            }

            @Override
            public void onError(Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(call, response, e);
                mView.hideLoading();
                mView.uploadFileFailed();
            }
        });
    }

    Thread delImageThread = new Thread(new Runnable() {
        @Override
        public void run() {
            DataCleanManager.deleteDir(new File(FileUtils.PATH_SDCARD + FileUtils.PATH_IMAGE_COMPRESS));
        }
    });
}
